package code.starivan.leetcode;

/**
 * Created by Ivan on 2015/10/21.
 */
/*
Given a 2D board and a word, find if the word exists in the grid.

        The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

        For example,
        Given board =

        [
        ["ABCE"],
        ["SFCS"],
        ["ADEE"]
        ]
        word = "ABCCED", -> returns true,
        word = "SEE", -> returns true,
        word = "ABCB", -> returns false.
*/

public class N079_WordSearch {
    public static void test(){
        char[][] board=new char[][]{{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
        String word="ABCB";

        System.out.println(new N079_WordSearch().exist(board,word));
    }

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0) {
            return false;
        }

        int r = board.length;
        int c = board[0].length;
        boolean[][] visited = new boolean[r][c];
        int i = 0, j = 0;
        int s = 0;
        char[] str=word.toCharArray();
        for (i = 0; i < r; ++i) {
            for (j = 0; j < c; ++j) {
                if (board[i][j] == str[s]) {
                    visited[i][j]=true;
                    if(serach(board,i,j,str,s+1,visited)){
                        return true;
                    }

                    visited[i][j]=false;
                }
            }
        }

        return false;
    }

    private boolean serach(char[][] board, int i, int j, char[] str, int s, boolean[][] visited) {
        if (s == str.length) {
            return true;
        }

        int[][] dirs = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
        for (int d = 0; d < dirs.length; ++d) {
            int ni = i + dirs[d][0];
            int nj = j + dirs[d][1];

            if (ni >= 0 && ni < board.length
                    && nj >= 0 && nj < board[0].length &&
                    visited[ni][nj] == false &&
                    board[ni][nj] == str[s]
                    ) {
                visited[ni][nj] = true;
                if(serach(board,ni,nj,str,s+1,visited)){
                    return true;
                }

                visited[ni][nj] = false;
            }
        }

        return false;
    }
}
